package com.ybear.ybutils.utils;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.ybear.ybutils.utils.log.LogUtil;

import java.util.Locale;

/**
 * 语言环境工具类
 */
public class LocaleUtil {
    /**
     * 获取语言环境
     * @return  语言环境
     */
    public static Locale getLocale() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            LocaleList list = LocaleList.getDefault();
            if( !list.isEmpty() ) return list.get( 0 );
        }
        return Locale.getDefault();
    }

    /**
     改变App语言
     调用：
         1.{@link Application}中初始化一次，因为可能有些sdk会通过{@link Application#getResources()}获取资源
         2.自己创建的基类 BaseActivity.onStart() 时调用，这样能保证每次进入新的界面可以实时更新
     重启app后生效，也可以使用 {@link Activity#recreate()} 重建当前页面
     @param context     Context or Activity
     @param language    参考本地化语言的命名。eg：zh, en, jp, ko, ar ...
     eg:{@link Locale#ENGLISH#getLanguage()}
     */
    public static boolean changeAppLanguage(Context context, @NonNull String language) {
        String logTag = "ChangeAppLanguage";
        if ( context == null || TextUtils.isEmpty( language ) ) {
            LogUtil.d( logTag, "The language arg passed in is null." );
            return false;
        }
        try {
            Resources res = context.getResources();
            Configuration config = res.getConfiguration();
            Locale newLocale = new Locale( language );
            Locale oldLocale = null;
            //获取当前环境的Locale
            if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ) {
                try {
                    oldLocale = config.getLocales().get( 0 );
                }catch(Exception e) {
                    e.printStackTrace();
                }
            }
            //低版本兼容
            if( oldLocale == null ) oldLocale = config.locale;
            //检查语言环境
            if( oldLocale == null || !language.equals( oldLocale.getLanguage() ) ) {
                if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 ) {
                    //语言环境
                    config.setLocale( newLocale );
                    //语言布局方向
                    config.setLayoutDirection( newLocale );
                }else {
                    //兼容 JELLY_BEAN_MR1 以下版本
                    config.locale = newLocale;
                }
                //更新配置
                res.updateConfiguration( config, res.getDisplayMetrics() );
                LogUtil.d( logTag, "The language has been changed to '%s'", language );
            }else {
                //已经设置，跳过
                LogUtil.d( logTag, "The skip change language." );
            }
            //更新View的语言布局方向
            if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 ) {
                if( context instanceof Activity ) {
                    View decorView = ((Activity)context).getWindow().getDecorView();
                    int ld = config.getLayoutDirection();
                    if( decorView != null && decorView.getLayoutDirection() != ld ) {
                        decorView.setLayoutDirection( ld );
                        LogUtil.d( logTag, "The layout direction of DecorView been changed." );
                    }else {
                        //已经设置，跳过
                        LogUtil.d( logTag, "The skip change layout direction of DecorView." );
                    }
                }
            }
            return true;
        }catch(Exception e) {
            e.printStackTrace();
        }
        //更新失败
        LogUtil.d( logTag, "Failed to change the '%s' locale. Procedure", language );
        return false;
    }

    /**
     * 获取本机语言
     * @param locale        Locale
     * @param isCountry     是否返回语言的地区，eg：CN, TW(China)
     * @return              语言。eg：zh-CN
     */
    public static String getLanguage(Locale locale, boolean isCountry) {
        return isCountry ?
                String.format( "%s-%s", locale.getLanguage(), locale.getCountry() ) :
                locale.getLanguage();
    }

    public static String getLanguage(boolean isCountry) {
        return getLanguage( getLocale(), isCountry );
    }

    /**
     * 获取本机语言
     * @return  语言。eg：zh
     */
    public static String getLanguage() { return getLanguage( false ); }

    /**
     是否为Rtl布局
     @param locale  Locale
     @return        是否为Rtl布局
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static boolean isRtlLayout(Locale locale) {
        return TextUtils.getLayoutDirectionFromLocale( locale ) == View.LAYOUT_DIRECTION_RTL;
    }

    /**
     是否为Rtl布局
     @return        是否为Rtl布局
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static boolean isRtlLayout() { return isRtlLayout( getLocale() ); }

    /**
     是否为Ltr布局
     @param locale  Locale
     @return        是否为Ltr布局
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static boolean isLtrLayout(Locale locale) {
        return TextUtils.getLayoutDirectionFromLocale( locale ) == View.LAYOUT_DIRECTION_LTR;
    }
    /**
     是否为Ltr布局
     @return        是否为Ltr布局
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static boolean isLtrLayout() { return isRtlLayout( getLocale() ); }
}
